import { Controller, Get, HttpCode, HttpStatus, Query } from '@nestjs/common';
import { Public } from 'src/common/public.decorator';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import * as crypto from 'crypto';
import { WxService } from './wx.service';
import { AuthDto } from './dto/wx.dto';

@ApiTags('wx')
@Controller('wx')
export class WxController {
  // 这里是你的 token，与微信公众平台设置的一致
  private readonly token = 'ZYL_123456';

  constructor(private readonly wxService: WxService) {}

  @Public()
  @Get('check')
  @ApiOperation({ summary: '微信签名校验' })
  @HttpCode(HttpStatus.OK)
  check(@Query() query) {
    console.log('---query--', query);
    const { signature, timestamp, nonce, echostr } = query;
    // 排序拼接字符串
    const tmpArr = [this.token, timestamp, nonce].sort();
    const tmpStr = tmpArr.join('');

    // 使用 SHA1 算法进行加密
    const sha1 = crypto.createHash('sha1');
    sha1.update(tmpStr, 'utf8');
    const hash = sha1.digest('hex');

    // 对比签名
    if (hash === signature) {
      // 签名验证成功，返回 echostr
      return echostr;
    } else {
      // 签名验证失败，返回错误或空字符串
      return '';
    }
  }

  @Public()
  @Get('auth')
  @ApiOperation({ summary: '微信授权' })
  @HttpCode(HttpStatus.OK)
  auth(@Query() authDto: AuthDto) {
    return this.wxService.auth(authDto);
  }
}
